package com.googlecode.dgwt.client.dojo.data.model;

import java.util.Map.Entry;

import com.googlecode.dgwt.client.dojo.data.format.ValueFormatter;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class KeyValueColumn<Key,Value> extends StoreColumnBase<Entry<Key,Value>, Object> {

    private Class<?> columnType;

    public KeyValueColumn() {
        super();
    }

    @SuppressWarnings("unchecked")
    public KeyValueColumn(ValueFormatter<?> formatter) {
        super((ValueFormatter<Object>)formatter);
    }

    public KeyValueColumn(boolean readOnly) {
        super(readOnly);
    }

    @SuppressWarnings("unchecked")
    public KeyValueColumn(boolean readOnly, ValueFormatter<?> formatter) {
        super(readOnly, (ValueFormatter<Object>)formatter);
    }

    @Override
    protected Object onGetValue(Entry<Key,Value> item) {
        switch (getColumnIndex()) {
            case 0: {
                return item.getKey();
            }
            case 1: {
                return item.getValue();
            }
        }
        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void onSetValue(Entry<Key,Value> item, Object value) {
        switch (getColumnIndex()) {
            case 0: {
                if (item instanceof KeyValueEntry) {
                    ((KeyValueEntry<Object,Object>)item).setKey(value);
                }
                break;
            }
            case 1: {
                item.setValue((Value) value);
                break;
            }
        }
    }

    @Override
    public Class<?> getColumnType() {
        return columnType;
    }

    public void setColumnType(Class<?> classType) {
        if (classType == null){
            classType = Object.class;
        }
        this.columnType = classType;
        updateFormatter();
    }

}
